package ctl

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"os/signal"
	"syscall"
)

var (
	CmdGracefullyStop chan bool
	//MysqlGracefullyStop chan bool
	GracefullyStop bool
)

func init() {
	CmdGracefullyStop = make(chan bool, 1)
	//MysqlGracefullyStop = make(chan bool, 1)
	GracefullyStop = false
}

// HandleSignals 监听退出服务动作
func HandleSignals() error {
	signCh := make(chan os.Signal, 1)
	signal.Notify(signCh, os.Interrupt, syscall.SIGHUP, syscall.SIGTERM)

	var sig os.Signal
	select {
	case s := <-signCh:
		sig = s
	}
	logrus.WithFields(logrus.Fields{"location": "signal", "method": "handleSignals"}).Info(fmt.Sprintf("Caught signal:%s", sig))

	if sig == syscall.SIGQUIT {
		logrus.WithFields(logrus.Fields{"location": "signal", "method": "handleSignals"}).Warn("litter received SIGQUIT, but it will not quit, because it is multiple co-routines program, it can automatically close its useless co-routine.")
		return nil
	}

	GracefullyStop = true
	logrus.WithFields(logrus.Fields{"location": "signal", "method": "handleSignals"}).Info("Gracefully shutting down...")
	// 标记优雅退出
	close(CmdGracefullyStop)
	//close(MysqlGracefullyStop)
	return nil
}
